from python_app.railsim.libapi import *
import pygame
import random
from python_app.tracks_model import TrackModel, TurnoutJunctionModel
from python_app.track_topology import TrackTopology

motorProperty = ElectricMotorProperty.create_value(
    "YJ85-A".encode("utf8"),
    ELECTRIC_MOTOR_TYPE.THREE_PHASED_ASYNC,
    1250,
    11852,
    2662,
    0.92,
    4.85,
)

loco_ptr, loco = ElectricLocomotive.create(5, 25, 25 * 6, 1.20, 6, motorProperty)
assert loco_ptr is not None
assert loco.motorNum == 6
assert loco.motorProperty.name == b"YJ85-A"
loco_num = 1

loco_ptr2, loco2 = ElectricLocomotive.create(5, 25, 25 * 4, 1.20, 4, motorProperty)
assert loco2.motorNum == 4

wagons = []
car_property = RailroadCarProperty.create(
    "N6".encode("utf-8"),
    RAILROAD_CAR_TYPE.RAILROAD_CAR_TYPE_FLATCAR,
    12.5,
    100,
    21.5,
    60,
)
for i in range(60):
    wagon = RailroadWagon.create(car_property)
    print(hex(ctypes.addressof(wagon.property.contents)))
    wagon.load = 50.0
    wagon.id = i
    wagons.append(wagon)

train = Train.create([loco, loco2], wagons)

# track = Track.create()

# track.add_train(train)


WIDTH = 1100
HEIGHT = 600
FPS = 30

# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)


class Player(pygame.sprite.Sprite):
    # sprite for the Player
    def __init__(self):
        # this line is required to properly create the sprite
        pygame.sprite.Sprite.__init__(self)
        # create a plain rectangle for the sprite image
        self.image = pygame.Surface((50, 10))
        self.image.fill(GREEN)
        # find the rectangle that encloses the image
        self.rect = self.image.get_rect()
        # center the sprite on the screen
        # self.rect.center = (WIDTH / 2, HEIGHT / 2)

    def update(self):
        track_id, percentage = train.get_position()
        if track_id not in mapping:
            return
        track_start, track_end = mapping[track_id]
        # 求两个二维点end到start中间percentage位置的坐标

        self.rect.center = (
            track_start[0] + (track_end[0] - track_start[0]) * percentage,
            track_start[1] + (track_end[1] - track_start[1]) * percentage,
        )

        if self.rect.left > WIDTH:
            self.rect.right = 0


# initialize pygame and create window
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Sprite Example")
clock = pygame.time.Clock()

all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)

extra_surface = pygame.Surface((WIDTH, HEIGHT))
# sprites_surface = pygame.Surface((WIDTH, HEIGHT), depth=24)

pygame.draw.line(extra_surface, (255, 255, 255), (20, 4), (WIDTH - 20, 4), 2)

topo = TrackTopology()
topo.draw(extra_surface)
track_objs = topo.route1.get_track_objects(topo.topology)
mapping = {
    track_obj.id: (start_pos, end_pos) for track_obj, start_pos, end_pos in track_objs
}
print("track_objs", track_objs)

screen.blit(extra_surface, (0, 0))
# Game loop
running = True
s = 0

#
route = Route.create(
    [item for item, _1, _2 in track_objs], [DIRECTION.DIRECTION_DOWN] * len(track_objs)
)
train.set_route(route)

while running:
    # keep loop running at the right speed
    clock.tick(FPS)
    # Process input (events)
    for event in pygame.event.get():
        # check for closing window
        if event.type == pygame.QUIT:
            running = False
    # track.update()
    train.update()
    # Update
    all_sprites.update()
    s += 1
    if s == 100:
        train.trainDynamics.state = TRAIN_STATE.TRAIN_STATE_ACCEL
    screen.blit(extra_surface, (0, 0))
    # Draw / render
    # sprites_surface.fill(BLACK)
    dirty_rects = all_sprites.draw(screen)

    # 更新屏幕的指定区域（精灵所在区域）
    pygame.display.update(dirty_rects)
    # all_sprites.draw(sprites_surface)
    # *after* drawing everything, flip the display
    pygame.display.flip()

pygame.quit()
